import os
import PyPDF2
import docx
import pandas as pd
from typing import Dict, Any
import json
import yaml
from app.core.config import settings

class DocumentProcessor:
    """文档处理工具类，用于处理各种文档文件"""
    
    @staticmethod
    async def process_document(file_path: str) -> Dict[str, Any]:
        """处理文档文件并提取内容"""
        try:
            file_ext = os.path.splitext(file_path)[1].lower()
            
            if file_ext == '.pdf':
                return await DocumentProcessor._process_pdf(file_path)
            elif file_ext == '.docx':
                return await DocumentProcessor._process_docx(file_path)
            elif file_ext in ['.xlsx', '.xls']:
                return await DocumentProcessor._process_excel(file_path)
            elif file_ext == '.txt':
                return await DocumentProcessor._process_txt(file_path)
            elif file_ext in ['.json', '.yaml', '.yml']:
                return await DocumentProcessor._process_config(file_path)
            else:
                raise ValueError(f"不支持的文件类型: {file_ext}")
        except Exception as e:
            print(f"处理文档时出错: {str(e)}")
            return {"error": str(e)}
    
    @staticmethod
    async def _process_pdf(file_path: str) -> Dict[str, Any]:
        """处理PDF文件"""
        content = []
        with open(file_path, 'rb') as file:
            pdf_reader = PyPDF2.PdfReader(file)
            for page in pdf_reader.pages:
                content.append(page.extract_text())
        return {
            "type": "pdf",
            "content": "\n".join(content),
            "page_count": len(pdf_reader.pages)
        }
    
    @staticmethod
    async def _process_docx(file_path: str) -> Dict[str, Any]:
        """处理Word文档"""
        doc = docx.Document(file_path)
        content = []
        for para in doc.paragraphs:
            content.append(para.text)
        return {
            "type": "docx",
            "content": "\n".join(content)
        }
    
    @staticmethod
    async def _process_excel(file_path: str) -> Dict[str, Any]:
        """处理Excel文件"""
        content = {}
        excel_file = pd.ExcelFile(file_path)
        for sheet_name in excel_file.sheet_names:
            df = pd.read_excel(excel_file, sheet_name=sheet_name)
            content[sheet_name] = df.to_dict('records')
        return {
            "type": "excel",
            "content": content
        }
    
    @staticmethod
    async def _process_txt(file_path: str) -> Dict[str, Any]:
        """处理文本文件"""
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        return {
            "type": "txt",
            "content": content
        }
    
    @staticmethod
    async def _process_config(file_path: str) -> Dict[str, Any]:
        """处理配置文件"""
        file_ext = os.path.splitext(file_path)[1].lower()
        with open(file_path, 'r', encoding='utf-8') as file:
            if file_ext == '.json':
                content = json.load(file)
            else:  # yaml/yml
                content = yaml.safe_load(file)
        return {
            "type": file_ext[1:],
            "content": content
        } 